#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

int main()
{
    int sv[2];
    pid_t pid;
    char buffer_send[100];
    char buffer_receive[100];
    //创建套接字对
    if(socketpair(AF_UNIX,SOCK_STREAM,0,sv) == -1)
    {
        perror("socketpair");
        return 1;
    }
    pid = fork();
    if(pid == -1)
    {
        perror("fork");
        close(sv[0]);
        close(sv[0]);
        close(sv[1]);
        return 1;
    }
    else if(pid == 0)
    {
        //子进程
        close(sv[1]);//关闭写套接字
        //先接收来自父进程的数据
        ssize_t bytesRead = read(sv[0],buffer_receive,sizeof(buffer_receive));
        if(bytesRead == -1)
        {
            perror("read in child");
            return 1;
        }
        buffer_receive[bytesRead] = '\0';
        printf("Child received: %s\n",buffer_receive);
        //其后向父进程发送数据
        strcpy(buffer_send,"Message from child!");
        ssize_t bytesWritten = write(sv[0],buffer_send,strlen(buffer_send));
        if(bytesWritten == -1)
        {
            perror("write in child");
            return 1;
        }   
        close(sv[0]);
    }
    else
    {
        //父进程
        close(sv[0]);//关闭读套接字
        //先向子进程发送数据
        strcpy(buffer_send,"Message from parent!");
        ssize_t bytesWritten = write(sv[1],buffer_send,strlen(buffer_send));
        if(bytesWritten == -1)
        {
            perror("write in parent");
            return 1;
        }
        //然后接收来自子进程的数据
        ssize_t bytesRead = read(sv[1],buffer_receive,sizeof(buffer_receive));
        if(bytesRead == -1)
        {
            perror("read in parent");
            return 1;
        }
        buffer_receive[bytesRead] = '\0';
        printf("Parent received: %s\n",buffer_receive);
        close(sv[1]);
    }
    return 0;
}